import React from 'react'
import { Button, Input, Space, Table as TableAnt } from 'antd'
import { EditableCell, EditableRow } from './Editable'
import Highlighter from 'react-highlight-words'
import { Map } from 'immutable'
import _ from 'lodash'
import tableStyles from './table.less'
import { SearchOutlined } from '@ant-design/icons'

//字段排序
export const columnSorter = (a, b) => {
  if ((_.isEmpty(a)) && (!_.isEmpty(b))) {
    return 1
  }
  if ((!_.isEmpty(a)) && (_.isEmpty(b))) {
    return -1
  }
  if ((!_.isEmpty(a)) && (!_.isEmpty(b))) {
    if (a.localeCompare && b.localeCompare) {
      return a.localeCompare(b)
    }
  }
  return a === b ? 0 : (a > b ? 1 : -1)
}

class Table extends React.PureComponent {

  state = { searchColumns: Map({}) }

  getColumnSearchProps = (dataIndex, render) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          autoComplete={'off'}
          spellCheck={false}
          ref={node => { this.searchInput = node }}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(dataIndex, selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Space size={'small'}>
          <Button
            style={{ width: 90 }}
            type={'primary'}
            size={'small'}
            icon={<SearchOutlined/>}
            onClick={() => this.handleSearch(dataIndex, selectedKeys, confirm)}
          >
            查询
          </Button>
          <Button
            style={{ width: 90 }}
            size={'small'}
            onClick={() => this.handleReset(dataIndex, clearFilters)}
          >
            重置
          </Button>
        </Space>
      </div>
    ),
    filterIcon: filtered => <SearchOutlined className={filtered ? 'ant-table-filter-trigger active' : ''}/>,
    onFilter: (value, record) => (record[dataIndex] || '').toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => this.searchInput.select())
      }
    },
    render: render || (text =>
        /*
        1.自动省略，暂不支持和排序筛选一起使用，render放在排序筛选后
        添加render后可以显示自动省略title，但影响单元格筛选部分变色
        临时处理方式，不筛选时可显示title，筛选时不能显示title，可显示单元格筛选部分变色
        2.不覆盖原column render
         */
        this.state.searchColumns.has(dataIndex)
          ? <Highlighter
            highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
            searchWords={[this.state.searchColumns.get(dataIndex)]}
            autoEscape
            textToHighlight={(text || '').toString()}
          />
          : text
    ),
  })

  handleSearch = (dataIndex, selectedKeys, confirm) => {
    confirm()
    const searchText = selectedKeys[0]
    let searchColumns
    if (searchText) {
      searchColumns = this.state.searchColumns.set(dataIndex, searchText)
    } else {
      searchColumns = this.state.searchColumns.delete(dataIndex)
    }

    this.setState({ searchColumns })
  }

  handleReset = (dataIndex, clearFilters) => {
    clearFilters()
    const searchColumns = this.state.searchColumns.delete(dataIndex)
    this.setState({ searchColumns })
  }

  getColumnsSearchProps = (columns) => {
    return columns.map(column => {
      if (column.children) {
        //支持多级表头
        column.children = this.getColumnsSearchProps(column.children)
      }
      if (column.search) {
        let { key, dataIndex } = column
        if (!key && Array.isArray(dataIndex)) {
          dataIndex = dataIndex.join('.')
        }
        return { ...column, ...this.getColumnSearchProps(key || dataIndex, column.render) }
      }
      return column
    })
  }

  render () {
    const { columns, editable, dataSource, ...props } = this.props

    //是否可编辑
    const components = editable ? {
      components: {
        body: {
          row: EditableRow,
          cell: EditableCell,
        },
      }
    } : {}

    return (
      <TableAnt
        rowClassName={(record, index) => {
          return `${index % 2 === 1 ? tableStyles.odd : ''} ${editable ? 'editable-row' : ''}`
        }}
        size={'small'}
        pagination={{
          showTotal: (total, range) => `第${range[0]}-${range[1]}条/共${total}条`,
          defaultPageSize: 100,
          showSizeChanger: true,
          pageSizeOptions: [10, 20, 50, 100, 200, 500],
        }}
        bordered
        showSorterTooltip={false}
        columns={this.getColumnsSearchProps(columns)}
        dataSource={dataSource || []}
        {...components}
        {...props}
      />
    )
  }
}

export default Table